package org.elanfox.intellicommunity.msg.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import lombok.extern.slf4j.Slf4j;
import org.elanfox.intellicommunity.msg.server.config.NettyProperties;
import org.elanfox.intellicommunity.msg.server.handler.MsgServerHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author allan
 * @version 1.0.0
 * @date 2019/12/11
 */
@Slf4j
@Service
public class NettyServer {
    @Autowired
    private NettyProperties nettyProperties;
    @Autowired
    private MsgServerHandler serverHandler;

    private final EventLoopGroup bossGroup = new NioEventLoopGroup();
    private final EventLoopGroup workerGroup = new NioEventLoopGroup();

    private Channel channel;

    public ChannelFuture start() {
        ChannelFuture f = null;
        try {
            //ServerBootstrap负责初始化netty服务器，并且开始监听端口的socket请求
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
//                    .option(ChannelOption.SO_BACKLOG, nettyProperties.getBacklog())
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
//                    .localAddress(new InetSocketAddress(nettyProperties.getHost(), nettyProperties.getPort()))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
//                            为监听客户端read/write事件的Channel添加用户自定义的ChannelHandler
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
//                            pipeline.addLast(new StringDecoder());
//                            pipeline.addLast(new StringEncoder());
//                            pipeline.addLast(new EqMsgDecoder());
                            socketChannel.pipeline().addLast(serverHandler);
                        }
                    });

            f = b.bind(nettyProperties.getPort()).sync();
            channel = f.channel();
        } catch (Exception e) {
            log.error("Netty server start up Error!", e);
        } finally {
            if (f != null && f.isSuccess()) {
                log.info("Netty server listening " + nettyProperties.getHost() + " on port " + nettyProperties.getPort() + " and ready for connections...");
            }
        }
        return f;
    }

    public void close() {
        log.info("Shutdown Netty Server...");
        if (channel != null) {
            channel.close();
        }
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        log.info("Shutdown Netty Server Success!");
    }
}
